package org.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        nativeQuery(em,"SHOW TABLES");
        nativeQuery(em,"SHOW COLUMNS FROM EMPLOYEE");
        nativeQuery(em,"SHOW COLUMNS FROM EMP_TASK");
        nativeQuery(em,"SHOW COLUMNS FROM TASK");
        persistEmployee(em);
        nativeQuery(em,"SELECT * FROM EMPLOYEE");
        nativeQuery(em,"SELECT * FROM EMP_TASK");
        nativeQuery(em,"SELECT * FROM TASK");
        em.close();

    }

    private static void persistEmployee(EntityManager em){
        try {
            Employee e1 = new Employee();
            e1.setName("employee name 1");
            Task task1 = new Task("task 1","description 1");
            Task task2 = new Task("task 2","description 2");

            Employee e2 = new Employee();
            e2.setName("employee name 2");
            Task task3 = new Task("task 3","description 3");

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            e1.addTask(task1,format.parse("2021-01-02"));
            e1.addTask(task2,format.parse("2021-03-21"));

            e2.addTask(task3,format.parse("2021-05-22"));
            em.getTransaction().begin();
            em.persist(task1);
            em.persist(task2);
            em.persist(task3);
            em.persist(e1);
            em.persist(e2);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.close();
        }
    }
    private static void nativeQuery(EntityManager em,String s){
        System.err.println("-------------------- " + s + " --------------------");
        Query query = em.createNativeQuery(s);
        List list = query.getResultList();
        for (Object o : list) {
            if(o instanceof Object[]){
                System.err.println(Arrays.toString((Object[])o));
            }else{
                System.err.println(o);
            }
        }
    }
}
